<template>
  <RouterView />
  <van-tabbar safe-area-inset-bottom v-model="active" @change="onChange">
    <van-tabbar-item>
      <span>首页</span>
      <template #icon>
        <img v-if="active == 0" src="@/assets/home_active.png" />
        <img v-else src="@/assets/home.png" />
      </template>
    </van-tabbar-item>
    <van-tabbar-item
      ><span>学习</span
      ><template #icon>
        <img v-if="active == 1" src="@/assets/learn_active.png" />
        <img v-else src="@/assets/learn.png" /> </template
    ></van-tabbar-item>
    <van-tabbar-item>
      <span>测试</span>
      <template #icon>
        <img v-if="active == 2" src="@/assets/testing_active.png" />
        <img v-else src="@/assets/testing.png" />
      </template>
    </van-tabbar-item>
    <van-tabbar-item
      ><span>培训</span>
      <template #icon>
        <img v-if="active == 3" src="@/assets/training_active.png" />
        <img v-else src="@/assets/training.png" /> </template
    ></van-tabbar-item>
    <van-tabbar-item
      ><span>我的</span>
      <template #icon>
        <img v-if="active == 4" src="@/assets/my_active.png" />
        <img v-else src="@/assets/my.png" /> </template
    ></van-tabbar-item>
  </van-tabbar>
</template>

<script setup>
import { RouterView, useRouter, useRoute } from "vue-router";
import { ref, watch } from "vue";
import { onMounted } from "vue";

const router = useRouter();
const route = useRoute();
const active = ref(0);

// 路由路径与导航栏索引的映射
const routeMapping = {
  "/index": 0,
  "/learning": 1,
  "/test": 2,
  "/training": 3,
  "/my": 4,
};

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    // 查找包含当前路径的路由
    for (const path in routeMapping) {
      if (newPath.startsWith(path)) {
        active.value = routeMapping[path];
        return;
      }
    }
    active.value = 0; // 默认值
  }
);

// 组件挂载时设置初始激活状态
onMounted(() => {
  // 查找包含当前路径的路由
  for (const path in routeMapping) {
    if (route.path.startsWith(path)) {
      active.value = routeMapping[path];
      break;
    }
  }
});

const onChange = (index) => {
  switch (index) {
    case 0:
      router.push("/index");
      break;
    case 1:
      router.push("/learning");
      break;
    case 2:
      router.push("/test");
      break;
    case 3:
      router.push("/training");
      break;
    case 4:
      router.push("/my");
      break;
  }
};
</script>
